#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2018/10/23 11:23
# @Author  : Tang Yang
# @Site    : 
# @File    : image_utils.py

import cv2
import numpy as np


MIN_MATCH_COUNT = 4


def get_homography(img_1, img_2):
    """
    计算两幅图片之间的单应矩阵
    :param img_1:
    :param img_2:
    :return:
    """
    sift = cv2.xfeatures2d.SIFT_create()
    kp1, des1 = sift.detectAndCompute(img_1, None)
    kp2, des2 = sift.detectAndCompute(img_2, None)

    FLANN_INDEX_KDTREE = 0
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)

    flann = cv2.FlannBasedMatcher(index_params, search_params)

    matches = flann.knnMatch(des1, des2, k=2)

    good = []
    for m, n in matches:
        if m.distance < 0.7 * n.distance:
            good.append(m)

    if len(good) > MIN_MATCH_COUNT:
        src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
        dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

        homo, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

        return homo
    else:
        raise RuntimeError("Not enough matches are found - %d/%d" % (len(good), MIN_MATCH_COUNT))